* This do-file assembles outcomes related to revenue, cost, and profits
* NOTE: In Y3 Rabi only includes revenue; no profit or cost

tempfile profits

forvalues y = 1/3 {

	local fileK "${k`y'}/Farm/profits.dta"
	local fileR "${r`y'}/Farm/profits.dta"
	local fileP "${k`y'}/Farm/plots.dta"

*** Farm Profits

	use hhid Khh_profit_prod Khh_revenue_prod Khh_revenue_sold Khh_tot_cost ///
		using "`fileK'", clear
	if `y'<3 merge 1:1 hhid using "`fileR'", ///
		keepusing(Rhh_profit_prod Rhh_revenue_prod Rhh_revenue_sold Rhh_tot_cost)
	else if `y'==3 merge 1:1 hhid using "`fileR'", ///
		keepusing(Rhh_revenue_sold)
	drop if _m==2 		// 1 obs is missing hhid
	drop _merge

	egen earn_profit = rowtotal(*hh_profit_prod)
	egen earn_revenue = rowtotal(*hh_revenue_prod)
	egen earn_sales = rowtotal(*hh_revenue_sold)
	egen earn_cost = rowtotal(*hh_tot_cost)
	drop Rhh_* Khh_*
	
	* Winsorize variables (by year to avoid mingling with phone survey)
	foreach var of varlist earn_* {
		winsor `var', gen(`var'_win5) highonly p(.05)
	}
	
	gen byte year = `y'

	if `y'>1 append using `profits'
save `profits', replace

*** Scale of Farm Operation

	use hhid plotno status_kharif plot_area_acre using "`fileP'", clear
	
	* Winsorize plot area
	winsor plot_area_acre, gen(farm_area_acre_win5) highonly p(.05)
	* Restrict to farmed plots (owned, rented, or sharecropped)
	keep if inlist(status_kharif,1,4,5)
	collapse (sum) farm_area_acre=plot_area_acre farm_area_acre_win5, by(hhid) fast
	
	gen byte year = `y'
	
merge 1:1 hhid year using `profits', update nogen
save `profits', replace
}

* Fillin no profits/acres
merge m:1 hhid using "$admin_data/survey_list.dta", assert(match using) nogen
drop village
	
	* Fill in; add roster variables
	fillin hhid year
	drop if missing(year) // fills in missing values as well
	merge m:1 hhid using "$out_data/survey_drops.dta", assert(match) keepusing(drop_*) nogen
	
	recode earn* farm* (.=0) if (year==1) | (year==2 & drop_k2==0) | (year==3 & drop_k3==0)
	drop drop_* _fillin

order hhid year earn* farm*
save "$out_data/outcome_profits", replace
